package 中兴机试;

import java.util.ArrayList;
import java.util.Arrays;

public class 中兴机试 {
    public static void main(String[] args) {
        int[] a = {0, 1, 0, 0, 1, 1, 0, 0};
        int[] b = {3, 5, 12, 6, 13, 23, 30, 38};
        sort(a, b);
        func(a, b);
    }

    private static void sort(int[] a, int[] b) {
        for (int i = 0; i < a.length; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (b[i] > b[j]) {
                    swap(a, i, j);
                    swap(b, i, j);
                }
            }
        }
    }

    private static void swap(int[] a, int i, int j) {
        a[i] = a[i] ^ a[j];
        a[j] = a[i] ^ a[j];
        a[i] = a[i] ^ a[j];
    }

    private static void func(int[] a, int[] b) {
        //找到开头和a[i]=1的i和结尾
        ArrayList<Integer> idxList = new ArrayList<>();
        if (a[0] == 0)
            idxList.add(0);
        for (int i = 0; i < a.length; i++) {
            if (a[i] == 1)
                idxList.add(i);
        }
        if (a[a.length - 1] == 0)
            idxList.add(a.length - 1);

        //最后的结果，分段处理
        int res = 0;
        for (int i = 0; i < idxList.size() - 1; i++) {
            res += getMinDis(a, b, idxList.get(i), idxList.get(i + 1));
        }
        System.out.println(res);
    }

    private static int getMinDis(int[] a, int[] b, int w, int e) {
        int res = 0;
        //开头和结尾
        if ((a[w] == 1 && a[e] == 0) || (a[w] == 0 && a[e] == 1)) {
            for (int i = w; i < e; i++) {
                res += Math.abs(b[i + 1] - b[i]);
            }
        }
        //中间过程，两边都是1的，全部的减去最长的
        if (a[w] == 1 && a[e] == 1) {
            int[] len = new int[e - w];
            int idx = 0;
            for (int i = w; i < e; i++) {
                len[idx++] = b[i + 1] - b[i];
            }
            Arrays.sort(len);
            for (int aLen : len) {
                res += aLen;
            }
            res -= len[len.length - 1];
        }
        return res;
    }
}